Contents
  1. 1. 实例 2
    1. 1.1. UseCase.java:
    2. 1.2. PasswordUtils.java:
    3. 1.3. UseCaseChecker.java

实例 2

UseCase.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package lianxi;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UseCase {
public int id() default -1;

public String description() default "No desciption";
}

PasswordUtils.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package lianxi;

import java.util.ArrayList;
import java.util.List;
import java.lang.*;

public class PasswordUtils {

@UseCase (id = 47, description = "密码必须包含至少一个数字")
public boolean vaildPassword(String password){
return password.matches("\\w*\\d\\w*");
}

@UseCase(id = 48)
public String encryptPassword(String password){
return new StringBuilder(password).reverse().toString();
}

@UseCase(id = 49, description = "新密码不能和曾经用过的密码重复")
public boolean checkForNewPassword(List<String> prePasswords, String password){
return !prePasswords.contains(password);
}

/*
* @deprecated不准备使用这个方法了,用其他的方法代替它吧
*/

@Deprecated
public void deprecated(){}

@SuppressWarnings({"unused", "rawtypes"})
public void unsafeMethod(){
List unsafeList = new ArrayList<String>();
}
}

UseCaseChecker.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package lianxi;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
* 用例检测的注解处理器
*/


public class UseCaseChecker {

public static void trackUseCases(List<Integer> useCases, Class<?> cl)
{

for(Method m : cl.getDeclaredMethods())//遍历cl的所有方法
{
UseCase uc = m.getAnnotation(UseCase.class);//获得方法的注解
if(uc != null)
{
System.out.println("找到用例:" + uc.id () + " " + uc.description ());//输出该方法的注解的参数
useCases.remove(new Integer(uc.id()));
}
}
for(int i : useCases)
{
System.out.println ("警告-- 缺失用例:" + i);
}
}
public static void main(String[] args){
List<Integer> useCases = new ArrayList<Integer>();
Collections.addAll(useCases, 47, 48, 49, 50);
trackUseCases(useCases, PasswordUtils.class);
}
}
注意:如果trackUseCases()方法不声明为static的话会:
Cannot make a static reference to the non-static method trackUseCases(List<Integer>, Class<?>) from the type UseCaseChecker

输出:
找到用例:49 新密码不能和曾经用过的密码重复
找到用例:48 No desciption
找到用例:47 密码必须包含至少一个数字
警告-- 缺失用例:50

Contents
  1. 1. 实例 2
    1. 1.1. UseCase.java:
    2. 1.2. PasswordUtils.java:
    3. 1.3. UseCaseChecker.java